package com.grsu.phonestation.web;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.grsu.phonestation.domain.Admin;
import com.grsu.phonestation.domain.Client;
import com.grsu.phonestation.domain.UserActive;
import com.grsu.phonestation.service.UserActiveService;

@Controller
@RequestMapping("/history")
public class HistoryController {

	@Autowired
	@Qualifier("userActiveServiceImpl")
	private UserActiveService<UserActive> userActiveService;

	@RequestMapping(value = { "/", " " }, method = { RequestMethod.GET })
	public ModelAndView listUserActive(HttpSession session, Model model) {

		ModelAndView mav = new ModelAndView();

		Object userObject = session.getAttribute("user");
		if (userObject != null) {

			if (userObject instanceof Client) {

				Client user = (Client) userObject;

				List<UserActive> userActives = userActiveService
						.getUserActiveClient(user);

				mav.addObject("user", user);
				mav.addObject("userActives", userActives);
				mav.setViewName("history");
			}
			if (userObject instanceof Admin) {

				Admin user = (Admin) userObject;

				List<UserActive> userActives = userActiveService
						.listUserActives();

				mav.addObject("user", user);
				mav.addObject("userActives", userActives);
				mav.setViewName("admin.history");

			}
		} else {
			mav = new ModelAndView("redirect:/login");
			mav.setViewName("login");
		}

		return mav;
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public ModelAndView deliteService(@PathVariable("id") Integer userActiveId,
			HttpSession session, Model model) {

		ModelAndView mav = new ModelAndView("redirect:/history");

		userActiveService.removeUserActive(userActiveId);

		return mav;
	}

	@RequestMapping(value = "/search", method = RequestMethod.POST)
	public ModelAndView listUserActiveForPeriod(String user, String beginPeriod, String endPeriod, HttpSession session, Model model){
		
		ModelAndView mav = new ModelAndView("redirect:/history");
		
		List<UserActive> userActives = userActiveService.listUserActivesClientForPeriod(user, beginPeriod, endPeriod);

				mav.addObject("userActives", userActives);
				mav.setViewName("admin.history");

		return mav;
		
	}

}
